package com.chuan.base.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.shuodao.common.util.RequestUtil;

public class FileToZip {
	 private static final Logger LOGGER = LoggerFactory.getLogger(FileToZip.class);
	 private FileToZip(){}  

	    private String zipFileName;      // 目的地Zip文件
	    private String[] sourceFileName;   //源文件（带压缩的文件或文件夹）
	    private String dirName;
	    public FileToZip(String zipFileName,String[] sourceFileName,String dirName)
	    {
	        this.zipFileName=zipFileName;
	        this.sourceFileName=sourceFileName;
	        this.dirName=dirName;
	    }
	    
	    public void zip() throws Exception
	    {
	    	LOGGER.info("压缩中...");
	        //创建zip输出流
	        ZipOutputStream out = new ZipOutputStream( new FileOutputStream(zipFileName));
	        
	        //创建缓冲输出流
	        BufferedOutputStream bos = new BufferedOutputStream(out);
	        
	        File sourceFile[] = new File[this.sourceFileName.length];
	       for(int i = 0 ; i < sourceFileName.length ; i++) {
	    	   sourceFile[i] = new File(RequestUtil.mergeUrl(dirName, sourceFileName[i]));
	       }
	       
	        //调用函数
	        compress( out,bos,sourceFile);
	        
	        bos.close();
	        out.close();
	        LOGGER.info("压缩完成");
	        
	    }
	    
	    /**
	     * 
	     * @param out
	     * @param bos
	     * @param sourceFile
	     * @param base		// 文件新名称
	     * @throws Exception
	     */
	    public void compress( ZipOutputStream out,BufferedOutputStream bos,File[] sourceFile) throws Exception
	    {
	        if(sourceFile.length > 0)  {
	        	for (File file : sourceFile) {
	        			if(file==null || file.getTotalSpace() < 100) continue;
	        		    out.putNextEntry( new ZipEntry(file.getName()) );
		  	            FileInputStream fos = new FileInputStream(file);
		  	            BufferedInputStream bis = new BufferedInputStream(fos);
		  	            
		  	            int tag;
		  	            //将源文件写入到zip文件中
		  	            while((tag=bis.read())!=-1)
		  	            {
		  	                bos.write(tag);
		  	            }
		  	            bos.flush();
		  	            LOGGER.info("被压缩的文件为:"+file.getName());
		  	            bis.close();
		  	            fos.close();
				}
	        	
	        }
	    }
	
	    public  void fileUpload(InputStream is, OutputStream os) throws Exception{
	    	 
			byte[] b = new byte[1024 * 1024 * 10];
			int length = 0;
			while (true) {
				length = is.read(b);
				if (length < 0)
					break;
				os.write(b, 0, length);
			}
			os.flush();
			is.close();
			os.close();
		   
	  }
	    public void download(HttpServletResponse response ) {
			
			try {
				
				File logFile = new File(this.zipFileName);
				response.setContentType("application/zip");
//				response.setContentType("application/octet-stream");
				response.addHeader("Content-Disposition", "attachment;filename=user_address.zip");
				response.setCharacterEncoding("utf-8");
				// 将文件输入流写入response的输出流中
				fileUpload(new FileInputStream(logFile), response.getOutputStream());
				
			}catch(Exception e) {
				e.printStackTrace();
			}
			
		}
		public void clear(String folderName) {
			delFolder(folderName);
			LOGGER.info(folderName+"下的文件已经清空!");
		}
		
		
		//删除文件夹
		//param folderPath 文件夹完整绝对路径

		     public  void delFolder(String folderPath) {
		     try {
		        delAllFile(folderPath); //删除完里面所有内容
		        String filePath = folderPath;
		        filePath = filePath.toString();
//		        java.io.File myFilePath = new java.io.File(filePath);
//		        myFilePath.delete(); //删除空文件夹
		     } catch (Exception e) {
		       e.printStackTrace(); 
		     }
		}

		//删除指定文件夹下所有文件
		//param path 文件夹完整绝对路径
		   public  boolean delAllFile(String path) {
		       boolean flag = false;
		       File file = new File(path);
		       if (!file.exists()) {
		         return flag;
		       }
		       if (!file.isDirectory()) {
		         return flag;
		       }
		       String[] tempList = file.list();
		       File temp = null;
		       for (int i = 0; i < tempList.length; i++) {
		          if (path.endsWith(File.separator)) {
		             temp = new File(path + tempList[i]);
		          } else {
		              temp = new File(path + File.separator + tempList[i]);
		          }
		          if (temp.isFile()) {
		             temp.delete();
		          }
		          if (temp.isDirectory()) {
		             delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
		             delFolder(path + "/" + tempList[i]);//再删除空文件夹
		             flag = true;
		          }
		       }
		       return flag;
		     }
		   
		  
}
